﻿using System.Xml;
using Microsoft.Extensions.Configuration;

namespace 开发自己的配置提供者.自己练习;

public class XmlConfigurationProvider:FileConfigurationProvider
{
    public XmlConfigurationProvider(FileConfigurationSource source) : base(source)
    {
    }

    public override void Load(Stream stream)
    {
        var data =new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        var xmlDoc = new XmlDocument();
        xmlDoc.Load(stream);
        var xmlNodeList = xmlDoc.SelectNodes("/configuration/connectionStrings/add");
        //读取配置connnectionString
        foreach (var xmlNode in xmlNodeList.Cast<XmlNode>())
        {
            var name = xmlNode.Attributes["name"].Value;
            var connectionStrValue = xmlNode.Attributes["connectionString"].Value;
            var providerNameValue = xmlNode.Attributes["providerName"].Value;
            data.Add($"{name}:connectionString",connectionStrValue);
            data.Add($"{name}:providerName",providerNameValue);
            
        } 
        //读取配置appSettings
        var xmlNodeListAppSetting = xmlDoc.SelectNodes("/configuration/appSettings/add");
        foreach (var xmlNode in xmlNodeListAppSetting.Cast<XmlNode>())
        {
            var key = xmlNode.Attributes["key"].Value;
            key = key.Replace('.', ':');
            var value = xmlNode.Attributes["value"].Value;
            data.Add(key,value);
        }

        using var xmlNodeListName = xmlDoc.SelectNodes("/configuration/name/add");
        data.Add(xmlNodeListName[0].Attributes["name"].Value,xmlNodeListName[0].Attributes["value"].Value);

        Data = data;
    }
}